<template>
  <span ref="textRef" v-show="!overflow" class="one-line-text">
    {{ text || '-' }}
  </span>
  <u-tooltip v-if="overflow" :title="text" :mouse-enter-delay="1">
    <span class="one-line-text">
      {{ text || '-' }}
    </span>
  </u-tooltip>
</template>
<script>
import { ref, watch, nextTick } from 'vue'

export default {
  name: 'OneLineText',
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const overflow = ref(false)
    const textRef = ref(null)

    const handleTextReload = () => {
      if (textRef.value) {
        const clonedNode = textRef.value.cloneNode(true)
        clonedNode.style.overflow = 'visible'
        clonedNode.style.display = 'inline-block'
        clonedNode.style.width = 'auto'
        clonedNode.style.whiteSpace = 'nowrap'
        clonedNode.style.visibility = 'hidden'
        document.body.appendChild(clonedNode)
        if (textRef.value.offsetWidth < clonedNode.offsetWidth) {
          overflow.value = true
        }
        document.body.removeChild(clonedNode)
      }
    }

    watch(() => props.text, () => {
      nextTick(() => {
        handleTextReload()
      })
    }, { immediate: true })

    return {
      overflow,
      textRef
    }
  }
}
</script>
<style lang="less">
.one-line-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
